<?php


namespace app\api\library\order\orderDetail;


use app\api\model\MallCollage;
use app\api\model\MallOrder;
use app\api\model\MallUser;
use think\facade\Db;

class V
{
    public static function run($param)
    {
        $userId  = _checkEmptyParam($param[ 'userId' ], '用户ID不能为空');
        $orderId = _checkEmptyParam($param[ 'orderId' ], '订单ID不能为空');
        $where   = [
            ['id', '=', $orderId],
            ['user_id', '=', $userId],
            ['delete_time', '=', null],
        ];
        $order   = Db::name('mall_order')
            ->where($where)
            ->field('id,goods_id,order_no,order_price,order_status,collage_status,refund_status,collage_id,address_id,phone,receiver,address,receipt_time,pay_time,submit_refund_time,refund_time,express_company,express_no,express_no,delivery_time,create_time,remark')
            ->find();
        if (empty($order)) {
            _outPut(204, '', '订单不存在');
        }
        $order[ 'collage' ] = Db::name('mall_collage')
                ->field('collage_id,user_id,collage_no,goods_id,start_time,end_time,finish_time,fail_time,failure_reward,success_reward,collage_num+1 as collage_num,join_num+1 as join_num')
                ->where([['collage_id', '=', $order[ 'collage_id' ]]])
                ->find() ?? [];
        $users1             = Db::name('mall_order')->where([['u_collage_id', '=', $order[ 'collage_id' ]], ['order_status', 'in', '1,10,30,40,50,60']])->field('user_id,pay_time')->select()->toArray();
        $users2             = [];
        if ($order[ 'collage' ][ 'finish_time' ] ?? 0 > 0) {
            $users2 = Db::name('mall_order')->where([['u_collage_id', '=', $order[ 'collage_id' ]], ['order_status', '=', '70'], ['refund_time', '>', $order[ 'collage' ][ 'finish_time' ]]])->field('user_id,pay_time')->select()->toArray();
        }
//        $users2  = Db::name('mall_order')->where([['u_collage_id', '=', $order[ 'collage_id' ]], ['order_status', '=', '70']])->field('user_id,pay_time')->select();
        $users   = array_merge($users1, $users2);
        $users[] = Db::name('mall_order')->where([['collage_id', '=', $order[ 'collage_id' ]]])->field('user_id,pay_time')->find();
        if ( !empty($users)) {
            $userIds          = array_column($users, 'user_id');
            $users            = array_column($users, null, 'user_id');
            $order[ 'users' ] = MallUser::where([['id', 'in', $userIds]])->field('id,name,avatar_url')->select()->toArray();
            foreach ($order[ 'users' ] as $key => &$value) {
                $value[ 'pay_time' ] = $users[ $value[ 'id' ] ][ 'pay_time' ] ?? '';
            }
        }
        $order[ 'goods' ] = Db::name('mall_goods')
            ->where([['id', '=', $order[ 'goods_id' ]]])
            ->field('id,title,logo,remark')
            ->find();
        _outPut(200, $order);
    }
}